package com.tiyende.kash.loop.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonActivity
import com.tiyende.kash.loop.configs.TiyendeApiPath
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.databinding.TiyendeActivityFeedbackBinding
import com.tiyende.kash.loop.databinding.TiyendeActivityFeedbackQuestionTypeItemBinding
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.adapter.TiyendeFeedbackImageAdapter
import com.tiyende.kash.loop.ui.contract.IViewContract
import com.tiyende.kash.loop.ui.presenter.TiyendeFeedbackPresenter
import com.tiyende.kash.loop.ui.presenter.TiyendeImageUploadPresenter
import com.tiyende.kash.loop.utils.imgcovert.ImageConvert
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import org.json.JSONObject
import java.io.File

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/27 13:45
 * @Annotation：意见反馈
 */
class TiyendeFeedbackActivity: CommonActivity(), IViewContract.ITiyendeFeedbackView, IViewContract.ITiyendeImageUploadView {
    lateinit var binding: TiyendeActivityFeedbackBinding
    private var presenter: TiyendeFeedbackPresenter? = null
    private var upLoadPresenter: TiyendeImageUploadPresenter? = null

    //图片列表
    private var pictureAdapter: TiyendeFeedbackImageAdapter? = null

    //图片压缩后存储的临时文件
    private var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    companion object {
        private const val INTENT_KEY_STAR_COUNT = "starCount"
        fun start(context: Context, count: String? = "") {
            val intent = Intent(context, TiyendeFeedbackActivity::class.java)
            intent.putExtra(INTENT_KEY_STAR_COUNT, count)
            context.startActivity(intent)
        }
    }

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityFeedbackBinding.inflate(layoutInflater)
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeTextTitleVisibility(View.GONE)
        setTiyendeSwitchLangBtnRes(R.mipmap.tiyende_language_icon)
        eventRemark = "Feedback_Page"

        initFeedbackRecyclerView()

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                TiyendeLogger.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    TiyendeLogger.e(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        //最多只能选三张
                        if (pictureAdapter?.itemCount == 3){
                            pictureAdapter?.removeItem(0)
                        }
                        val imgObj = JSONObject()
                        imgObj.put("isDefault",false)
                        imgObj.put("imgPath",localPath)
                        pictureAdapter?.addLastItem(imgObj)

                        showTiyendeLoading()
                        if (upLoadPresenter == null){
                            upLoadPresenter = TiyendeImageUploadPresenter(this)
                        }
                        upLoadPresenter?.submitUploadImageAction(localPath)
                    }
                }

            } else {
                TiyendeLogger.e("No media selected")
            }
        }
    }

    override fun initTiyendeListener() {
        super.initTiyendeListener()
        //输入框监听
        binding.userAdviseRemark.addTextChangedListener(IRemarkChangeListener)
        binding.userAdviseRemark.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && binding.userAdviseRemark.text.toString().isNotEmpty()){
                addEventPointRequestAction(TiyendeEventPointType.FORM.TIYENDE_FORM_USER_FEEDBACK_DESCRIBE,binding.userAdviseRemark.text.toString())
            }
        }

        //提交
        binding.btnSubmit.setOnClickListener {
            //问题类型
            if (getSelectTypeItem() == null){
                showTiyendeToast(getString(R.string.tiyende_feedback_question_type))
                return@setOnClickListener
            }
            val remark = binding.userAdviseRemark.text.toString()
            if (remark.isEmpty()){
                showTiyendeToast(getString(R.string.tiyende_feedback_remark_title))
                return@setOnClickListener
            }
            showTiyendeLoading(isTOuchOut = false, isCancel = true)
            val params = JSONObject().addCommonParams().apply {
                put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_FEEDBACK_SUBMIT_PATH)
                put("type",getSelectTypeItem()?.optString("value"))//反馈类型
                put("opinion",remark)//反馈内容
            }
            val imgUrls = getSelectImageUrls()
            if (imgUrls.isNotEmpty()){
                params.put("images",imgUrls)
            }
            val starCount = getStarCount()
            if (starCount.isNotEmpty()){
                params.put("starNum",starCount)//从评价弹窗进入反馈页,需要传星级数量
            }

            presenter?.submitFeedbackAction(params)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_FEEDBACK_SUBMIT)
        }
    }

    override fun loadTiyendeData() {
        if (presenter == null){
            presenter = TiyendeFeedbackPresenter(this)
        }
        presenter?.loadFeedbackQuestionTypeListAction()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        pictureAdapter?.addFirstItem(imgObj)
    }

    /**
     * 初始化图片列表
     */
    private fun initFeedbackRecyclerView() {
        binding.userAdviseGridView.setHasFixedSize(false)
        binding.userAdviseGridView.isNestedScrollingEnabled = false
        binding.userAdviseGridView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.userAdviseGridView.layoutManager = layoutManager
        pictureAdapter = TiyendeFeedbackImageAdapter(binding.userAdviseGridView)
        binding.userAdviseGridView.adapter = pictureAdapter
        binding.userAdviseGridView.itemAnimator = DefaultItemAnimator()
        pictureAdapter?.setOnItemChildClickListener(CommonOnItemChildClickListener { parent, childView, position ->
            val item = pictureAdapter?.getItem(position)
            item?.let {
                when (childView.id) {
                    R.id.pictureRemove -> {//删除
                        if (!it.optBoolean("isDefault")) {
                            pictureAdapter?.removeItem(position)

                            //是否需要添加默认图片
                            var isAddDefault = true
                            pictureAdapter?.let { adapter ->
                                for (i in 0..<adapter.itemCount) {
                                    if (adapter.getItem(i).optBoolean("isDefault")) {
                                        isAddDefault = false
                                        break
                                    }
                                }
                                if (isAddDefault) {
                                    val imgObj = JSONObject()
                                    imgObj.put("isDefault", true)
                                    adapter.addFirstItem(imgObj)
                                }
                            }
                        }
                    }

                    R.id.pictureAddLayout -> {//选择图片
                        if (it.optBoolean("isDefault")) {
                            hasRequestPermissions()
                        }
                    }
                }
            }
        })
    }

    private val IRemarkChangeListener = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            val textLength = s?.length
        }
    }

    /**
     * 设置问题类型列表
     */
    private fun setQuestionTypeList(){
        binding.userAdviseFlexbox.removeAllViews()
        val typeList = presenter?.getUserAdviseTypeList()
        typeList?.let {
            for (i in 0..< it.size) {
                val item = it[i]
                val itemBinding = TiyendeActivityFeedbackQuestionTypeItemBinding.inflate(layoutInflater)
                itemBinding.textType.text = getString(item.optInt("title"))
                if (item.optBoolean("isSelect")){
                    itemBinding.textType.setTextColor(Color.parseColor("#FFFFFFFF"))
                    itemBinding.textType.shapeDrawableBuilder
                        .setSolidColor(Color.parseColor("#FF1F2937"))
                        .setStrokeColor(Color.parseColor("#FF3ED9AB"))
                        .intoBackground()
                } else {
                    itemBinding.textType.setTextColor(Color.parseColor("#FFFFFFFF"))
                    itemBinding.textType.shapeDrawableBuilder
                        .setSolidColor(Color.parseColor("#FF1F2937"))
                        .setStrokeColor(Color.parseColor("#FF334155"))
                        .intoBackground()
                }
                binding.userAdviseFlexbox.addView(itemBinding.root)
                itemBinding.textType.setOnClickListener {
                    if (item.optBoolean("isSelect")){
//                    item.put("isSelect",false)
//                    setQuestionTypeList()
                        return@setOnClickListener
                    }
                    for (index in 0..< typeList.size){
                        val obj = typeList[index]
                        if (index == i){
                            obj.put("isSelect",true)
                            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_FEEDBACK_QUESTION_TYPE,getString(obj.optInt("title")))
                        } else {
                            obj.put("isSelect",false)
                        }
                    }
                    setQuestionTypeList()
                }
            }
        }
    }

    /**
     * 获取选择的问题类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var selectItem: JSONObject? = null
        val typeList = presenter?.getUserAdviseTypeList()
        typeList?.let {
            for (i in 0..< it.size){
                val obj = it[i]
                if (obj.optBoolean("isSelect")){
                    selectItem = obj
                    break
                }
            }
        }
        return selectItem
    }

    /**
     * 获取上传的图片链接
     */
    private fun getSelectImageUrls(): String{
        var imgUrls = ""
        pictureAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                if (item.optBoolean("isDefault")){
                    continue
                }
                imgUrls = imgUrls + item.optString("imgUrl") + ","
            }
        }
        if (imgUrls.isNotEmpty()){
            imgUrls = imgUrls.substring(0,imgUrls.length - 1)
        }
        return imgUrls
    }

    /**
     * 获取评分数量
     */
    private fun getStarCount(): String {
        if (intent.extras == null){
            return ""
        }
        return if (intent.extras?.getString(INTENT_KEY_STAR_COUNT) == null) "" else intent.extras?.getString(INTENT_KEY_STAR_COUNT).toString()
    }

    /**
     * 设置意见反馈问题类型列表
     */
    override fun setTiyendeFeedbackQuestionTypeList(typeList: ArrayList<JSONObject>) {
        setQuestionTypeList()
    }

    /**
     * 图片上传成功，需要删除临时文件
     */
    override fun showTiyendeImageUploadSuccess(imgPath: String, imgUrl: String) {
        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_FEEDBACK_UPLOAD_IMAGE,imgUrl)
        val lastItem = pictureAdapter?.lastItem as JSONObject
        lastItem.put("imgUrl",imgUrl)

        destinationDirectory?.let {
            if (it.isFile){
                it.delete()
            }
        }
    }

    /**
     * 显示反馈提交成功
     */
    override fun showTiyendeFeedbackSubmitSuccess() {
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },500)
    }


    /**
     * 申请权限
     */
    private fun hasRequestPermissions(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_USER_FEEDBACK_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_USER_FEEDBACK_END)
    }
}